using System.Reflection;
using NLog.Web;
using SqlSugar;

using Infrastructure.Data;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// 配置 SqlSugar
builder.Services.AddScoped<ISqlSugarClient>(sp =>
{
    var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
    var db = new SqlSugarClient(new ConnectionConfig()
    {
        ConnectionString = connectionString,
        DbType = DbType.MySql,
        IsAutoCloseConnection = true,
        InitKeyType = InitKeyType.Attribute,
        ConfigureExternalServices = new ConfigureExternalServices
        {
            EntityService = (property, column) =>
            {
                if (property.PropertyType.IsEnum)
                {
                    column.DataType = "varchar(50)"; // MySQL使用varchar
                }
            }
        },
        MoreSettings = new ConnMoreSettings
        {
            IsAutoRemoveDataCache = true,
            IsAutoDeleteQueryFilter = true,
            IsWithNoLockQuery = true // MySQL特定优化
        }
    });

    // 开启SQL执行日志
    db.Aop.OnLogExecuting = (sql, parameters) =>
    {
        Console.WriteLine($"SQL: {sql}");
        if (parameters != null && parameters.Any())
        {
            Console.WriteLine($"Parameters: {string.Join(", ", parameters.Select(p => $"{p.ParameterName}={p.Value}"))}");
        }
    };

    // 开启错误日志
    db.Aop.OnError = (exp) =>
    {
        Console.WriteLine($"SQL Error: {exp.Message}");
        Console.WriteLine($"SQL Stack: {exp.StackTrace}");
    };

    try
    {
        // 测试数据库连接
        db.Open();
        db.Close();
    }
    catch (Exception ex)
    {
        throw;
    }

    return db;
});



//中介者
builder.Services.AddMediatR(cfg => {
    cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
});
//映射
builder.Services.AddAutoMapper(typeof(MappingProfile));
//日志
builder.Host.UseNLog();

var app = builder.Build();
//跨域
app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());



// Configure the HTTP request pipeline.

    app.UseSwagger();
    app.UseSwaggerUI();


app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

// 在应用启动时执行数据库迁移
using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    try
    {
        var db = services.GetRequiredService<ISqlSugarClient>();
        var initializer = new SqlSugarInitializer(db);
        initializer.Initialize();
        
        // 初始化Dapper
        var dapperInitializer = services.GetRequiredService<DapperInitializer>();
        dapperInitializer.Initialize();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.StackTrace);
    }
}

app.Run();